#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-11 下午2:58
from flask import Flask, g, request

app = Flask(__name__)

# 定义一个装饰器
def after_this_request(f):
    if not hasattr(g, 'after_request_callbacks'):
        g.after_request_callbacks = []
    g.after_request_callbacks.append(f)
    return f


# 请求结束后，统一调用所有的事件处理器
@app.after_request
def call_after_request_callbacks(response):
    for call_back in getattr(g, 'after_request_callbacks', ()):
        call_back(response)
    return response


# 一个使用场景
@app.before_request
def detect_user_language():
    language = request.cookies.get('user_lang')
    if language is None:
        language = "zh_CN"

        @after_this_request
        def remember_language(response):
            response.set_cookie('user_lang', language)

    g.language = language